package com.nikkerball.apps.darkhorse.rules;

import com.nikkerball.apps.darkhorse.model.base.NameObject;
import com.nikkerball.apps.darkhorse.model.security.Role;
import com.nikkerball.apps.darkhorse.model.security.SecurityContext;

/**
 * Represents a Rule
 *
 * @author marius (created on 2010-12-05)
 */
public class Rule {

    // ----- instance fields -----

    private Condition[] conditions;

    private RuleName name;

    // ----- constructors -----

    public Rule() {
    }

    public Rule(RuleName name, Condition[] conditions) {
        this.name = name;
        this.conditions = conditions;
    }

    // ----- public methods -----

    public Condition[] getConditions() {
        return this.conditions;
    }

    public void setConditions(Condition[] conditions) {
        this.conditions = conditions;
    }

    public RuleName getName() {
        return this.name;
    }

    public void setName(RuleName name) {
        this.name = name;
    }

    public boolean isSatisfied(SecurityContext securityContext, NameObject nameObject) {
        // Go Through the Conditions of the rule
        for (Condition condition : this.conditions) {
            if (ConditionType.Roles.equals(condition.getType())) {
                // Go through all the roles and makes sure that at least one of them applies
                for (Role role : securityContext.getRoles()) {
                    condition.evaluate(role.getName());
                    if (condition.isSatisfied()) {
                        break;
                    }
                }
            } else if (ConditionType.ObjectName.equals(condition.getType())) {
                condition.evaluate(nameObject.getName());
            }
            if (!condition.isSatisfied()) {
                return false;
            }
        }

        return true;
    }


}
